﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
using System.Timers;
namespace Server
{
    class Program
    {

        static void Main(string[] args)
        {

            Server server = new Server();
            server.RunServer();


            

        }

       
    }


    class Server
    {
        public bool waitToStart;
        public int currentQuestion;
        public List<ClientHandler> clients = new List<ClientHandler>();
        public Thread waitForClientsThread;

        public void RunServer()
        {
            Console.WriteLine("Sever Started");
            System.Timers.Timer aTimer = new System.Timers.Timer();
            List<string> questions = new List<string>();
            List<string> answers = new List<string>();
            List<string[]> choices = new List<string[]>();
            string[] choiceArray;
            currentQuestion = 0;
            waitToStart = true;
            aTimer.Elapsed += new ElapsedEventHandler(gameStartTimerEvent);
            aTimer.Interval = 10000;
            aTimer.Enabled = true;
            //set up questions and answers
            using (StreamReader reader = new StreamReader("Questions.txt"))
            {
                for (int q = 0; q < 10; q++)
                {
                    choiceArray = new string[4];
                    questions.Add(reader.ReadLine());

                    for (int i = 0; i < 4; i++)
                    {
                        choiceArray[i] = reader.ReadLine();
                    }
                    choices.Add(choiceArray);
                    answers.Add(reader.ReadLine());
                }
            }


            waitForClientsThread = new Thread(waitForClients);
            waitForClientsThread.Start();



            Thread inputStart = new Thread(startGameWithInput);
            inputStart.Start();
            while (waitToStart) ;
            Console.WriteLine("Not Accepting new clients");
            Question question = new Question();
            for (int i = 0; i < 10; i++)
            {
                question.question = questions[i];
                question.choices = choices[i];
                question.answer = answers[i];
                foreach (ClientHandler c in clients)
                {
                    Console.WriteLine("{0}: {1}", c.name, c.score);
                    c.sendQuestion(question);

                }
                Console.WriteLine("Press Enter to start next question");
                Console.ReadLine();
            }
        }
        public void startGameWithInput()
        {
            Console.ReadLine();
            waitToStart = false;
        }
        public void gameStartTimerEvent(object o, ElapsedEventArgs e)
        {
            waitToStart = false;
        }
        public void waitForClients()
        {
            IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
            TcpListener tcpListener = new TcpListener(ipAddress, 9001);
            tcpListener.Start();
            TcpClient client;
            while (true)
            {
                Console.WriteLine("Watiing");
                client = tcpListener.AcceptTcpClient();
                Console.WriteLine("ClientFound");
                ClientHandler clientHandler = new ClientHandler();
                clientHandler.startClient(client);
                clients.Add(clientHandler);
            }
        }
    }

    class ClientHandler
    {
        public string name;
        public int score;
        TcpClient client;
        System.IO.StreamWriter streamWriter;
        System.IO.StreamReader streamReader;
        Thread thread;
        public void startClient(TcpClient clientSocket)
        {
            score = 0;
            client = clientSocket;
            streamWriter = new System.IO.StreamWriter(client.GetStream());
            streamReader = new System.IO.StreamReader(client.GetStream());
            thread = new Thread(clientThread);
            thread.Start();
        }
        private void clientThread()
        {
            try
            {
                Console.WriteLine("Client Connected");
                string message;
                message = streamReader.ReadLine();
                name = message;
                Console.WriteLine("{0} has joined the game!", name);
            }
            catch
            {
                Console.WriteLine("Client connection failed");
            }
        }

        public void sendQuestion(Question question)
        {
            Thread thread = new Thread(questionThread);
            thread.Start(question);
        }
        
        private void questionThread(object q)
        {

            try
            {
                Question question = (Question)q;
                System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(client.GetStream());
                System.IO.StreamReader streamReader = new System.IO.StreamReader(client.GetStream());
                streamWriter.WriteLine(question.question);
                streamWriter.WriteLine(question.choices[0]);
                streamWriter.WriteLine(question.choices[1]);
                streamWriter.WriteLine(question.choices[2]);
                streamWriter.WriteLine(question.choices[3]);
                streamWriter.Flush();
                string answer = streamReader.ReadLine();
                if (answer == question.answer)
                {
                    score += 10;
                    //Console.WriteLine("{0} got the answer correct!", name);
                }
                else
                {
                    //Console.WriteLine("{0} got the answer wrong!", name);
                }
                Console.WriteLine("{0} has {1} points!", name, score);
            }
            catch
            {
                Console.WriteLine("Could not connect to {0}", name);
            }
            
    
        }
    }

    class Question
    {
        public string question;
        public string[] choices;
        public string answer;
    }

}
